package com.ruoyi.common.utils.sign

import org.slf4j.LoggerFactory
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
/**
 * Md5加密方法
 *
 * @author ruoyi
 */
object Md5Utils {
    private val log = LoggerFactory.getLogger(Md5Utils::class.java)
    private fun md5(s: String): ByteArray? {
        val algorithm: MessageDigest
        try {
            algorithm = MessageDigest.getInstance("MD5")
            algorithm.reset()
            algorithm.update(s.toByteArray(charset("UTF-8")))
            return algorithm.digest()
        } catch (e: Exception) {
            log.error("MD5 Error...", e)
        }
        return null
    }

    private fun toHex(hash: ByteArray?): String? {
        if (hash == null) {
            return null
        }
        val buf = StringBuffer(hash.size * 2)
        var i = 0
        while (i < hash.size) {
            if (hash[i].toInt() and 0xff < 0x10) {
                buf.append("0")
            }
            buf.append((hash[i].toInt() and 0xff).toLong().toString(16))
            i++
        }
        return buf.toString()
    }

    fun hash(s: String): String {
        return try {
            String(toHex(md5(s))!!.toByteArray(StandardCharsets.UTF_8), StandardCharsets.UTF_8)
        } catch (e: Exception) {
            log.error("not supported charset...{}", e)
            s
        }
    }
}
